import json
import urllib.request
import wave
import httpx
from datetime import datetime

from flask import Flask, request, jsonify
from pydub import AudioSegment
from vosk import Model, KaldiRecognizer

app = Flask(__name__)
not_need_words = ['请', '输入', '您', '听到', '的', '数字']

def download_mp3_old(url, save_path):
    try:
        # 下载文件
        urllib.request.urlretrieve(url, save_path)
        print("MP3 文件下载成功！")
    except Exception as e:
        print("下载失败:", e)

def download_mp3(url, save_path):
    try:
        # opener = urllib.request.build_opener()
        # opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36')]
        # # 下载文件
        # urllib.request.urlretrieve(url, save_path , opener.open)

        headers = {
            'Accept': '*/*',
            'Accept-Encoding': 'identity;q=1, *;q=0',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6',
            'Range': 'bytes=0-',
            'Referer': 'https://iam.pt.ouchn.cn/am/UI/Login',
            'Sec-Fetch-Dest': 'audio',
            'Sec-Fetch-Mode': 'no-cors',
            'Sec-Fetch-Site': 'cross-site',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'
        }
        with httpx.Client() as client:
            response = client.get(url, headers=headers)
            with open(save_path, 'wb') as f:
                f.write(response.content)

        print("MP3 文件下载成功！")
    except Exception as e:
        print("下载失败:", e)



def mp3_to_wav(mp3_file, wav_file):
    # 读取 MP3 文件
    audio = AudioSegment.from_mp3(mp3_file)
    # 将MP3文件导出为WAV格式（单声道、16kHz采样率、PCM编码）
    audio = audio.set_frame_rate(16000).set_channels(1)
    # 导出为 WAV 文件
    audio.export(wav_file, format="wav")


def recognize_wav(wav_file):
    # 载入语音识别模型
    model = Model("vosk-model-small-cn-0.22")

    # 初始化识别器
    recognizer = KaldiRecognizer(model, 16000)

    # 打开 WAV 文件
    wf = wave.open(wav_file, "rb")

    # 开始识别
    transcription = ""
    while True:
        data = wf.readframes(wf.getframerate())
        if len(data) == 0:
            break
        if recognizer.AcceptWaveform(data):
            result = recognizer.Result()
            print(result)
            transcription += result

    # 获取最终的识别结果
    result = recognizer.FinalResult()
    transcription += result

    # 将中文数字转换为阿拉伯数字
    # 替换特定字符串为空格
    for word in not_need_words:
        transcription = transcription.replace(word, "")
        # transcription = transcription.replace("请输入您听到的数字", " ")

    return transcription


def chinese_to_digits(chinese_text):
    chinese_digits_map = {
        '零': '0',
        ' ': '',
        '吧': '8',
        '把': '8',
        '一': '1',
        '二': '2',
        '三': '3',
        '四': '4',
        '是': '4',
        '似': '4',
        '五': '5',
        '六': '6',
        '七': '7',
        '八': '8',
        '九': '9'
    }

    digits = ''
    for char in chinese_text:
        if char in chinese_digits_map:
            digits += chinese_digits_map[char]
        else:
            digits += char

    return digits


# @app.route('/transcribe', methods=['POST'])
@app.route('/asr', methods=['POST'])
def transcribe():
    mp3_url = request.json['mp3_url']

    datetime_now = datetime.now().strftime("%Y%m%d%H%M%S")
    # 下载MP3文件
    mp3_file = f"{datetime_now}.mp3"
    download_mp3(mp3_url, mp3_file)

    # 转换MP3到WAV
    wav_file = f"{datetime_now}.wav"
    mp3_to_wav(mp3_file, wav_file)

    try:
        # 进行语音识别
        result = recognize_wav(wav_file)
        end = chinese_to_digits(result)
        print("result", end)
        data = json.loads(end)["text"]
        return jsonify({"data": data})
    except Exception as e:
        print("异常了", e)
        #  请 输入 您 听到 的 数字

        # 删除临时文件
        # os.remove(mp3_file)
        # os.remove(wav_file)

    return jsonify({"data": "result"})


if __name__ == '__main__':
    try:
        app.run(debug=False, port=5000, host='0.0.0.0')
    except Exception as e:
        print("程序异常退出", e)
